﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using Goway.Log4net;
using Newtonsoft.Json;

namespace Goway.StackingUC.SaveFile
{
    /// <summary>
    /// Json序列化与反序列化
    /// </summary>
    public static class JsonHelper
    {
        static JsonHelper()
        {
            JsonSerializerSettings setting = new JsonSerializerSettings();
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
                setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //setting.NullValueHandling = NullValueHandling.Ignore; 谨慎开启
                //setting.Converters.Add(new BoolConvert("是,否")); 谨慎开启
                return setting;
            });
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="JSONString">要反序列化的此对象字符串</param>
        /// <returns>反序列化生成的此对象</returns>
        public static T JSONDeserialize<T>(this string jsonString)
        {
            T result = default(T);

            try
            {
                result = JsonConvert.DeserializeObject<T>(jsonString);
            }
            catch (Exception ex)
            {
                JsonSerializerSettings setting = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                };

                string exMessage = JsonConvert.SerializeObject(ex, setting);
                LoggerHelper.Error(exMessage);
            }

            return result;
        }

        /// <summary>
        /// JSON序列化：null为""
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>序列化此对象生成的字符串</returns>
        public static string JSONSerialize<T>(this T Object)
        {
            string jsonString = "";
            try
            {
                jsonString = JsonConvert.SerializeObject(Object);
            }
            catch (Exception ex)
            {
                JsonSerializerSettings setting = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                };

                string exMessage = JsonConvert.SerializeObject(ex, setting);
                LoggerHelper.Error(exMessage);
            }

            return jsonString;
        }
    }
}
